package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.exception.BaseException;
import com.qujia.station.domain.Commodity;
import com.qujia.station.domain.InventoryDetails;
import com.qujia.station.mapper.InventoryDetailsMapper;
import com.qujia.station.service.CommodityService;
import com.qujia.station.service.InventoryDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("inventoryDetailsService")
@Slf4j
public class InventoryDetailsServiceImpl implements InventoryDetailsService {

    @Autowired
    private InventoryDetailsMapper inventoryDetailsMapper;

    @Autowired
    private CommodityService commodityService;

    @Override
    public List<InventoryDetails> selectInventoryDetailsList(Long batchId) {
        return inventoryDetailsMapper.selectInventoryDetailsList(batchId);
    }

    @Override
    public int saveInventoryDetails(InventoryDetails inventoryDetails) {
        log.info("保存库存盘点详情：[{}]", JSONObject.toJSONString(inventoryDetails));
        int i = inventoryDetailsMapper.insertSelective(inventoryDetails);
        if(i <= 0){
            throw new BaseException("库存盘点更新失败");
        }
        // 更新商品库存
        Commodity commodity = new Commodity();
        commodity.setCommodityId(inventoryDetails.getCommodityId());
        commodity.setInventory(inventoryDetails.getInventoryNum().longValue());
        commodityService.update(commodity);
        return i;
    }

    @Override
    public InventoryDetails selectInventoryDetailsSum(Long batchId) {
        return inventoryDetailsMapper.selectInventoryDetailsSum(batchId);
    }
}
